package server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * Used to send UDPMessenges to a Client
 * @author Andreas Mair
 *
 */
public class UDPMessenger 
{
	private DatagramSocket socket;
	private static UDPMessenger instance;
	
	private UDPMessenger() throws SocketException
	{
		this.socket=new DatagramSocket();
	}
	
	public synchronized static UDPMessenger getInstance() throws SocketException
	{
		if(instance==null)
		{
			instance=new UDPMessenger();
		}
		return instance;
	}
	
	/**
	 * Sends the UDPMessage strMessage to address:port
	 * @param address
	 * @param Port
	 * @param strMessage
	 * @return strMessage if address==null or Port==0 or an Exception occurred, otherwise null is returned
	 */
	public String sendMessage(InetAddress address, int port, String strMessage)
	{
		String strRet=strMessage;
		try
		{
			if(address!=null && port!=0)
			{
	            DatagramPacket packet1 = new DatagramPacket(strMessage.getBytes(), strMessage.getBytes().length, address, port);
				socket.send(packet1);
				strRet=null;
			}
		}
		catch (SocketException e) 
		{
			System.out.println("SocketException occured while trying to send '"+strMessage+"' to '"+address+"'!");
		}
		catch (IOException e) 
		{
			System.out.println("IOException occured while trying to send '"+strMessage+"' to '"+address+"'!");
		}
		return strRet;
	}
}
